/*
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-04-18 19:23:54
 * @LastEditTime: 2021-04-19 22:52:15
 * @LastEditors: zheng yiliang
 */
const mkdirp = require('mkdirp')
const multer = require('multer')

const path = require('path')

const sd = require('silly-datetime')

function multerFile () {
  // const upload = multer({ dest: 'static/upload' }) // 默认配置
  var storage = multer.diskStorage({
    // 配置上传的目录
    destination: function (req, file, cb) {
      cb(null, 'static/article') // 上传之前目录必须存在
    },
    // 修改上传后的文件名
    filename: function (req, file, cb) {
      // 1、获取后缀名
      let extname = path.extname(file.originalname)
      cb(null, file.fieldname + '-' + Date.now() + extname)
    }
  })
  var upload = multer({ storage: storage })
  return upload
}

function autoDirFile () { // 多文件上传
  // const upload = multer({ dest: 'static/upload' }) // 默认配置
  var storage = multer.diskStorage({
    // 配置上传的目录
    destination: async (req, file, cb) => {
      // 1、获取当前日期
      let day = sd.format(new Date(), 'YYYYMMDD')
      // 拼接路径
      let dir = path.join('static/article', day)
      // 2、按照日期生成图片存储目录 mkdirp 是个异步方法
      await mkdirp(dir)
      cb(null, dir) // 上传之前目录必须存在
    },
    // 修改上传后的文件名
    filename: function (req, file, cb) {
      // 1、获取后缀名
      let extname = path.extname(file.originalname)
      cb(null, file.fieldname + '-' + Date.now() + extname)
    }
  })
  var upload = multer({ storage: storage })

  return upload
}


let tools = {
  // multer: multerFile(),
  // dirMul: autoDirFile(),
  upload: autoDirFile()
  // cpUpload: multerFile().fields([{ name: 'pic1', maxCount: 1 }, { name: 'pic2', maxCount: 1 }])
}

module.exports = tools